package com.dh.controller;

import com.dh.common.ResultMapUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户登录控制层
 */
@Controller
public class UserController {
    /**
     * 跳转登录页面
     * 访问login跳转到login.html页面
     */
    @RequestMapping(value = "/login")
    public String login(){
        return "/login";
    }

    /**
     * 判断用户登录是否成功
     * @param username 用户名
     * @param password 密码
     * @return 验证成功
     */
    @RequestMapping(value = "/toLogin")
    @ResponseBody
    public Object toLogin(String username,String password){
        if(username==null||password==null){
            return ResultMapUtil.getHashMapLogin("用户名密码不能为空", "2");
        }
        //获取传入的用户和密码
        Subject subject = SecurityUtils.getSubject();
        //把获取的用户和密码，封装到token
        UsernamePasswordToken token= new UsernamePasswordToken(username,password);
        //通过捕获的异常，判断是否正确
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {//用户名不存在
            return ResultMapUtil.getHashMapLogin("用户名不存在", "2");
        }catch (IncorrectCredentialsException e){//密码错误
            return ResultMapUtil.getHashMapLogin("密码错误", "2");
        }
        return ResultMapUtil.getHashMapLogin("验证成功", "1");
    }

    /**
     * 跳转到后台首页
     * @return index.html
     */
    @RequestMapping(value = "/index")
    public String index(){
      return "/index";
    }

    /**
     * 注销跳转到登录页面
     * @return toLogin.html
     */
    @RequestMapping(value = "/logout")
    public String logout(){
        //获取session
        Subject subject = SecurityUtils.getSubject();
        //清除session
        subject.logout();
        //重定向到登录页面
        return "redirect:/login";
    }
}
